//
//  ChatDemoHelper.m
//  timelyRain
//
//  Created by Jiafei Wei on 2016/12/28.
//  Copyright © 2016年 Jiafei Wei. All rights reserved.
//

#import "ChatDemoHelper.h"
#import "HttpTool.h"
#import "BindTool.h"
#import "TimeReuest.h"
#import "MJExtension.h"
#import "RunSucessInfo.h"
#import "TimeChartRecord.h"
#import "ChartResut.h"
#import "MessageShow.h"
#import "TMessageCell.h"
#import "DataTool.h"
#import "BindTool.h"
#import "InterceptInfo.h"
#import "DbManage.h"
#if DEMO_CALL == 1
#import "DemoCallManager.h"
#endif
@interface ChatDemoHelper()
{
    
}

@end
@implementation ChatDemoHelper
static ChatDemoHelper *helper = nil;
+ (instancetype)shareHelper
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        helper = [[ChatDemoHelper alloc] init];
    });
    return helper;
}

- (id)init
{
    self = [super init];
    if (self) {
        [self initHelper];
    }
    return self;
}

- (void)initHelper
{
    [[EMClient sharedClient] addDelegate:self delegateQueue:nil];
    [[EMClient sharedClient].chatManager addDelegate:self delegateQueue:nil];//监听的方法操作
    [self getChartRecode];//获得所有的会话之后在获取所有的联系人
#if DEMO_CALL == 1
    [DemoCallManager sharedManager];
#endif
}
- (void)setMainVC:(MainVC *)mainVC
{
    _mainVC = mainVC;
    
#if DEMO_CALL == 1
    [[DemoCallManager sharedManager] setMainController:mainVC];
#endif
}
- (void)dealloc
{
    [[EMClient sharedClient] removeDelegate:self];
    [[EMClient sharedClient].chatManager removeDelegate:self];
}

- (void)didReceiveCmdMessages:(NSArray *)aCmdMessages//收到了
{
    //[_mainVC playSoundAndVibration];
    NSLog(@"我是历史聊天记录啊,什么时候啊");
    //收到消息之后要去通知，重新刷新界面啊，聊天和历史记录的界面
    for (EMMessage *message in aCmdMessages) {
        EMCmdMessageBody *cmdBody =(EMCmdMessageBody *)message.body;
        NSLog(@"cmdBody.action ====%@",cmdBody.action);
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:message.ext options:NSJSONWritingPrettyPrinted error:nil];
        NSString *str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSLog(@"didReceiveCmdMessages----=== %@",str);
        NSString *action =cmdBody.action;
        if ([action isEqualToString:@"update_char_record"]) {
            [self getChartRecode];//获取聊天记录
        }else if([action isEqualToString:@"recevie_txt"]){//收到的和发出去的都是用别人的id，这样子才保证是唯一的id
            //获取文本消息
            NSString *bindWathchPhone  =[BindTool share].bindInfo.phone_number;
            NSDictionary *dataAll=message.ext;
            NSDictionary *data =[dataAll objectForKey:@"data"];
            NSString *from =[data objectForKey:@"from"];
            NSString *to =[data objectForKey:@"to"];
            NSString *content =[data objectForKey:@"content"];
            NSNumber *time =[data objectForKey:@"date"];
            NSString *msgid =[data objectForKey:@"msgid"];
            NSLog(@"from===%@,to===%@,content==%@,msgid====%@",from,to,content,msgid);
            //插入数据库中去
            //判断一下to如果是自己的话，就改变一下from 活着to
            EMConversation *conversation =[[EMClient sharedClient].chatManager getConversation:from type:EMConversationTypeChat createIfNotExist:YES];
            EMMessage *message =[conversation loadMessageWithId:msgid error:nil];
            if (message==nil) {
                EMMessage *insertMessage = [EaseSDKHelper sendTextMessage:content to:from messageType:EMChatTypeChat messageExt:nil];
                [insertMessage setMessageId:msgid];
                if ([from isEqualToString:bindWathchPhone]) {
                    insertMessage.direction=EMMessageDirectionSend;
                }else{
                    insertMessage.direction=EMMessageDirectionReceive;
                }
                [insertMessage setTimestamp:[msgid longLongValue]];
                //insertMessage.status=EMMessageStatusSuccessed;
                [insertMessage setIsRead:false];
                [[EMClient sharedClient].chatManager importMessages:@[insertMessage] completion:nil];
                EMError *er =nil;
                insertMessage.conversationId =conversation.conversationId;
                NSLog(@"conversation.conversationId===%@",conversation.conversationId);
                [conversation insertMessage:insertMessage error:&er];
                if (er) {
                    NSLog(@"er-==========%@",er);
                }
                if (self.conversationListVC) {
                    [_conversationListVC refresh];
                }
                if (self.chatVC) {
                    NSLog(@"真是无语了啊啊");
                [_chatVC refrshCmdMessages:@[insertMessage]];
                }
                [_mainVC setupUnreadMessageCount];
            }else{
                NSLog(@"已经蠢仔了");
            }
        }else if([action isEqualToString:@"action_setting"]){
            
        }else if([action isEqualToString:@"action_notify"]){
            
        }else if([action isEqualToString:@"action_intercept_list"]){//拦截
            InterceptInfo *info =[[InterceptInfo alloc]init];
            NSDictionary *dataAll=message.ext;
            NSDictionary *data =[dataAll objectForKey:@"data"];
            info.from =[data objectForKey:@"from"];
            info.to =[data objectForKey:@"to"];
            info.content =[data objectForKey:@"content"];
            info.type =[data objectForKey:@"interceptType"];
            NSNumber *time =[data objectForKey:@"time"];
            info.time =[NSString stringWithFormat:@"%@",time];
            info.mark =@"黑名单";
            info.attribution=@"";
            info.isRead=@"NO";
            NSMutableArray *array =[NSMutableArray array];
            [array addObject:info];
            [[DbManage shareDbManage] insertInterceptInfoArray:array];//存入数据库
        }else if([action isEqualToString:@"call_phone"]){
            
        }else if([action isEqualToString:@"action_call_offhook"]){
            NSLog(@"我怎么发不出通知啊");
             NSNotification * notice = [NSNotification notificationWithName:@"receive_call_back" object:nil userInfo:@{@"1":@"123"}];
            [[NSNotificationCenter defaultCenter]postNotification:notice];
        }else if([action isEqualToString:@"send_txt"]){
            NSDictionary *dataAll=message.ext;
            NSDictionary *data =[dataAll objectForKey:@"data"];
            NSString *to =[data objectForKey:@"to"];
            NSString *content =[data objectForKey:@"body"];
            NSString *msg_id =[data objectForKey:@"msgid"];
            NSString *type =[data objectForKey:@"type"];
            EMMessage *insertMessage = [EaseSDKHelper sendTextMessage:content to:to messageType:EMChatTypeChat messageExt:nil];
            insertMessage.direction=EMMessageDirectionSend;
            [insertMessage setMessageId:msg_id];
            [insertMessage setTimestamp:[msg_id longLongValue]];
            insertMessage.status=EMMessageStatusSuccessed;
            [[EMClient sharedClient].chatManager importMessages:@[insertMessage] completion:nil];
        }
    }
}
#define SMS @"sms"
#define CALL @"call_record"
#define TXT @"txt"
#define AUDIO @"audio"
#define PIC @"picture"
//还少个定位
-(void)getChartRecode{
      __weak typeof(self) weakSelf = self;
    NSString *url =[apiUrl stringByAppendingString:getChatRecord];
    NSDictionary *param =@{@"user_id":[BindTool share].bindInfo.phone_number,@"page":@1};
    [HttpTool GET:url WithHeader:NO parameters:param success:^(id responseObject) {
        NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"--bgetChartRecodevvv--=== %@",str);
        NSString *bindWathchPhone  =[BindTool share].bindInfo.phone_number;
        RunSucessInfo *info =[RunSucessInfo mj_objectWithKeyValues:responseObject];
        if (info.status){
            TimeChartRecord *record = [TimeChartRecord mj_objectWithKeyValues:info.data];
            NSArray *dataRecords = record.records;
            for (ChartResut *resut in dataRecords) {
                NSString *type =resut.payload.bodies.type;
                NSString *msg_id = resut.msg_id;
                //查询数据库
                NSLog(@"from这都是什么的啊啊啊哈哈哈%@",resut.from);
                EMConversation *conversation =[[EMClient sharedClient].chatManager getConversation:resut.to type:EMConversationTypeChat createIfNotExist:YES];
                EMMessage *message =[conversation loadMessageWithId:msg_id error:nil];
                if (message==nil) {
                    if ([type isEqualToString:SMS]) {
                        //组装消息
                        NSLog(@"是sms的消息");
                        NSString *to=resut.to;
                        NSString *content = resut.payload.bodies.msg;
                        [content stringByAppendingString:@"(短信)"];
                        if ([resut.from isEqualToString:bindWathchPhone]) {
                            to =resut.to;
                        }else{
                            to =resut.from;
                        }
                        EMMessage *insertMessage = [EaseSDKHelper sendTextMessage:content to:to messageType:EMChatTypeChat messageExt:nil];
                        if ([resut.from isEqualToString:bindWathchPhone]) {
                            insertMessage.direction=EMMessageDirectionSend;
                        }else{
                            insertMessage.direction=EMMessageDirectionReceive;
                        }
                        [insertMessage setMessageId:msg_id];
                        insertMessage.status=EMMessageStatusSuccessed;
                        [insertMessage setTimestamp:[msg_id longLongValue]];
                        [[EMClient sharedClient].chatManager importMessages:@[insertMessage] completion:nil];
                        [conversation insertMessage:insertMessage error:nil];
                    }else if([type isEqualToString:CALL]){
                        int call_type =resut.payload.bodies.call_type;
                        int sendtime = [msg_id intValue];//时间搓
                        NSString *calldate =[DataTool timestampChaStringDate:sendtime];
                        NSString *content;
                        NSString *to=nil;
                        if (call_type==0) {//未接来电
                            content =[calldate stringByAppendingString:@"未接来电 (通话记录)"];
                            //to =resut.from;
                        }else if(call_type==1){//去电
                            content =[calldate stringByAppendingString:@"去电 (通话记录)"];
                            //to =resut.to;
                        }else{//来电
                            content =[calldate stringByAppendingString:@"来电 (通话记录)"];
                            //to =resut.from;
                        }
                        if ([resut.from isEqualToString:bindWathchPhone]) {
                            to =resut.to;
                        }else{
                            to =resut.from;
                        }
                        EMMessage *insertMessage = [EaseSDKHelper sendTextMessage:content to:to messageType:EMChatTypeChat messageExt:nil];
                        if ([resut.from isEqualToString:bindWathchPhone]) {
                            insertMessage.direction=EMMessageDirectionSend;
                        }else{
                            insertMessage.direction=EMMessageDirectionReceive;
                        }
                        [insertMessage setMessageId:msg_id];
                        insertMessage.status=EMMessageStatusSuccessed;
                        //[insertMessage setTimestamp:[msg_id longLongValue]];
                        [insertMessage setLocalTime:[msg_id longLongValue]];
                        [[EMClient sharedClient].chatManager importMessages:@[insertMessage] completion:nil];
                        [conversation insertMessage:insertMessage error:nil];
                    }else if([type isEqualToString:TXT]){
                        //组装消息
                        NSString *to =resut.to;
                        NSString *content = resut.payload.bodies.msg;
                        if ([resut.from isEqualToString:bindWathchPhone]) {
                            to =resut.to;
                        }else{
                            to =resut.from;
                        }
                        EMMessage *insertMessage = [EaseSDKHelper sendTextMessage:content to:to messageType:EMChatTypeChat messageExt:nil];
                        if ([resut.from isEqualToString:bindWathchPhone]) {
                            insertMessage.direction=EMMessageDirectionSend;
                            insertMessage.from=resut.to;
                        }else{
                            insertMessage.direction=EMMessageDirectionReceive;
                            insertMessage.from=resut.from;
                        }
                        [insertMessage setMessageId:msg_id];
                        [insertMessage setTimestamp:[msg_id longLongValue]];
                        insertMessage.status=EMMessageStatusSuccessed;
                        [[EMClient sharedClient].chatManager importMessages:@[insertMessage] completion:nil];
                        [conversation insertMessage:insertMessage error:nil];
                    }else if([type isEqualToString:AUDIO]){
                        //首先下载文件
                        NSLog(@"是音频消息========哈哈哈哈");
                        NSString *url = resut.payload.bodies.url;
                        int length = resut.payload.bodies.length;
                        NSString *filename = resut.payload.bodies.filename;
                        NSString *secret = resut.payload.bodies.secret;
                        [HttpTool downFileFromServerz:url fileName:filename completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
                            if (!error){
                                NSString *to=resut.to;
                                NSLog(@"to===========%@",to);
                                if ([resut.from isEqualToString:bindWathchPhone]) {
                                    to =resut.to;
                                }else{
                                    to =resut.from;
                                }
                                EMMessage *insertMessage =[EaseSDKHelper sendVoiceMessageWithLocalPath:[filePath absoluteString] duration:length to:to messageType:EMChatTypeChat messageExt:nil];
                                NSLog(@"是音频消息========下载完毕了");
                                if ([resut.from isEqualToString:bindWathchPhone]) {
                                    insertMessage.direction=EMMessageDirectionSend;
                                }else{
                                    insertMessage.direction=EMMessageDirectionReceive;
                                }
                                [insertMessage setMessageId:msg_id];
                                insertMessage.status=EMMessageStatusSuccessed;
                                //[insertMessage setTimestamp:[msg_id longLongValue]];
                                [insertMessage setLocalTime:[msg_id longLongValue]];
                                    [[EMClient sharedClient].chatManager importMessages:@[insertMessage] completion:nil];
                                [conversation insertMessage:insertMessage error:nil];
                                
                                NSLog(@"只是看看to是什么啊啊%@,from====%@",insertMessage.to,insertMessage.from);
                                
                            }
                        }];
                        //开始下载
                    }else if([type isEqualToString:PIC]){
                        
                    }
                }else{
                NSLog(@"是sms为什么已经存在了啊消息");
                }
            }
            if (weakSelf.conversationListVC) {
                [weakSelf.conversationListVC refreshDataSource];
            }
        }else{
            NSLog(@"为什么消息是为空的啊");
        }
    } failure:^(NSError *error) {
        
    }];
}
@end
